<?php
/**
 * Created by PhpStorm.
 * User: yangwang
 * Date: 2024-04-07
 * Time: 14:40
 */

namespace App\Service\Cruise\Merchant;


use App\Console\Commands\Cruise\ShopSelfCheckNotify;
use App\Models\Cruise\ShopSelfCheckNotifyConfigModel;
use App\Models\Shop\ShopModel;
use App\Remote\Rms\RmsUserRemote;
use App\Service\BaseService;
use Illuminate\Support\Facades\Log;

class ShopSelfCheckNotifyConfigService extends BaseService
{

    public static function info(int $shopId, int $uid): array
    {

        $data = ShopSelfCheckNotifyConfigModel::where(['shopId' => $shopId])->orderBy('id', 'desc')->first();
        if ($data) {
            $data = $data->toArray();
        } else {
            $res  = self::insert(ShopSelfCheckNotifyConfigModel::getDefaultConfig(), $shopId, $uid);
            $data = ShopSelfCheckNotifyConfigModel::where(['id' => $res['id']])->first()->toArray();
        }

        return [
            'id'                 => $data['id'],
            'notifySwitch'       => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::SWITCH_DESC_MAP,
                $data['notifySwitch']
            ),
            'notifyRoles'        => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::NOTIFY_ROLE_DESC_MAP,
                json_decode($data['notifyRoles'], 1)
            ),
            'notifyType'         => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::NOTIFY_TYPE_DESC_MAP,
                json_decode($data['notifyType'], 1)
            ),
            'kdNotifyTimeMap'    => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_KAIDANG_DESC_MAP,
                $data['kdNotifyTimeMap']
            ),
            'sdNotifyTimeMap'    => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_SHOUDANG_DESC_MAP,
                $data['sdNotifyTimeMap']
            ),
            'weekNotifyTimeMap'  => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_WEEKEND_DESC_MAP,
                $data['weekNotifyTimeMap']
            ),
            'monthNotifyTimeMap' => ShopSelfCheckNotifyConfigModel::buildMapOptions(
                ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_MONTH_DESC_MAP,
                $data['monthNotifyTimeMap']
            ),
        ];
    }

    public static function getBusinessTime(int $shopId): array
    {
        //todo
        $shopInfo = ShopModel::query()->where('id', $shopId)->first();
        if (!$shopInfo) {
            throw new \Exception('获取门店信息异常');
        }

        //系统存的分钟
        //如果为空设置为默认时间
        return [
            $shopInfo->startAt ?: ShopSelfCheckNotifyConfigModel::SHOP_BUSINESS_OPEN_DEFAULT,
            $shopInfo->endAt ?: ShopSelfCheckNotifyConfigModel::SHOP_BUSINESS_CLOSE_DEFAULT
        ];
    }

    public static function update(array $input, int $shopId, int $uid): array
    {
        $id = $input['id'];

        $update = [];

        if (isset($input['notifySwitch'])) {
            $update['notifySwitch'] = $input['notifySwitch'];
        }

        if ($input['notifyRoles'] ?? '') {
            $update['notifyRoles'] = $input['notifyRoles'];
        }

        if ($input['notifyType'] ?? '') {
            $update['notifyType'] = $input['notifyType'];
        }

        if (isset($input['kdNotifyTimeMap'])) {
            $update['kdNotifyTimeMap'] = $input['kdNotifyTimeMap'];
        }

        if (isset($input['sdNotifyTimeMap'])) {
            $update['sdNotifyTimeMap'] = $input['sdNotifyTimeMap'];
        }

        if (isset($input['weekNotifyTimeMap'])) {
            $update['weekNotifyTimeMap'] = $input['weekNotifyTimeMap'];
        }

        if (isset($input['monthNotifyTimeMap'])) {
            $update['monthNotifyTimeMap'] = $input['monthNotifyTimeMap'];
        }

        if ($update) {
            $update['updatedByUid'] = $uid;
            $update['updatedAt']    = time();

            ShopSelfCheckNotifyConfigModel::query()->where(['shopId' => $shopId])->update($update);
        }
        return [
            'id' => $id
        ];
    }


    public static function insert(array $input, int $shopId, int $uid): array
    {
        $id = ShopSelfCheckNotifyConfigModel::query()->insertGetId([
            'shopId'             => $shopId,
            'notifySwitch'       => $input['notifySwitch'] ?? ShopSelfCheckNotifyConfigModel::SWITCH_OPEN,
            'notifyRoles'        => json_encode(
                $input['notifyRoles'] ?? [
                    ShopSelfCheckNotifyConfigModel::NOTIFY_ROLE_1,
                    ShopSelfCheckNotifyConfigModel::NOTIFY_ROLE_2,
                    ShopSelfCheckNotifyConfigModel::NOTIFY_ROLE_3,
                    ShopSelfCheckNotifyConfigModel::NOTIFY_ROLE_4,
                ]
            ),
            'notifyType'         => json_encode(
                $input['notifyType'] ?? [
                    ShopSelfCheckNotifyConfigModel::NOTIFY_TYPE_APP,
                ]
            ),
            'kdNotifyTimeMap'    => $input['kdNotifyTimeMap'] ?? ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_MAP_1,
            'sdNotifyTimeMap'    => $input['sdNotifyTimeMap'] ?? ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_MAP_2,
            'weekNotifyTimeMap'  => $input['weekNotifyTimeMap'] ?? ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_MAP_3,
            'monthNotifyTimeMap' => $input['monthNotifyTimeMap'] ?? ShopSelfCheckNotifyConfigModel::NOTIFY_TIME_MAP_4,

            'createdAt'    => time(),
            'updatedAt'    => time(),
            'createdByUid' => $uid,//todo
            'updatedByUid' => $uid,//todo
        ]);
        return ['id' => $id];
    }

    /**
     * 根据数据库时间数值得出时间
     * @param $startAt
     * @param $endAt
     * @return string[]
     */
    public static function getShopBusinessTimeChangeByDb($startAt, $endAt): array
    {
        //开始时间取小时
        $startHour = floor($startAt / 60);
        $startHour = $startHour >= 10 ? $startHour : "0" . $startHour;
        //开始时间取分钟
        $startMinute = $startAt % 60;
        if ($startMinute == 0) {
            $startMinute = '00';
        }
        //结束时间取小时
        $endHour = floor($endAt / 60);
        $endHour = $endHour >= 10 ? $endHour : "0" . $endHour;
        //结束时间取分钟
        $endMinute = $endAt % 60;
        if ($endMinute == 0) {
            $endMinute = '00';
        }
        //分钟差
        //开始时间
        $startAt = $startHour . ":" . $startMinute;
        if ($endHour >= 24) {
            //次日
            $endHour = $endHour - 24;
            $endAt   = str_pad($endHour, 2, 0, STR_PAD_LEFT) . ":" . $endMinute;
        } else {
            $endAt = $endHour . ":" . $endMinute;
        }
        return ['startAt' => $startAt, 'endAt' => $endAt];
    }

    public static function getPushUserIds(int $shopId):array
    {
        $config = ShopSelfCheckNotifyConfigModel::query()->where('shopId',$shopId)->first();

        $notifyConfig = optional($config)->id
            ? [
                'notifySwitch'       => $config->notifySwitch,
                'notifyRoles'        => json_decode($config->notifyRoles, 1),
                'notifyType'         => json_decode($config->notifyType, 1),
                'kdNotifyTimeMap'    => $config->kdNotifyTimeMap,
                'sdNotifyTimeMap'    => $config->sdNotifyTimeMap,
                'weekNotifyTimeMap'  => $config->weekNotifyTimeMap,
                'monthNotifyTimeMap' => $config->monthNotifyTimeMap,
            ]
            : ShopSelfCheckNotifyConfigModel::getDefaultConfig();


        $userListKeyShopId = RmsUserRemote::usersInShops([$shopId]);
        $roleConfig = $userListKeyShopId['roleConfig'] ?? [];
        $shopUsers  = $userListKeyShopId['list'][$shopId] ?? [];

        if (empty($shopUsers) || empty($roleConfig)){
            Log::info("自检提醒未获取到可推送的用户,shopId:{$shopId}",$userListKeyShopId ?: []);
            return [];
        }

        $pushUsers = ShopSelfCheckNotify::getPushUsers(
            $notifyConfig['notifyRoles'], $roleConfig, $shopUsers
        );

        if (empty($pushUsers)){
            Log::info("自检提醒无符合推送的角色用户,shopId:{$shopId}",[
                'notifyConfig'=>$notifyConfig,
                'roleConfig'=>$roleConfig,
                'shopUsers'=>$shopUsers
            ]);
            return [];
        }

        return array_keys($pushUsers);
    }


}
